import { Notify } from 'vant';
import { ActionContext } from 'vuex';

import {
  appToken,
  baseStoreState,
} from './dict';
import { isObject } from './is';
import { $local } from './local';
import { $pathTo } from './pathTo';
import { request } from './request';

const lastBaseStore = $local(baseStoreState);
const Base = {
  token: '',//token
  info: null,//用户信息
  meta: {},//当前路由meta信息
  deviceInfo: {width:0,height:0,tabbarHeight:0,navbarHeight:0},
  netState: true,//app状态 离线app还是在线app
  metaState: false, //路由里面的meta信息状态，true的时候吧store的meta合并到到route
  updateState: false, //已经同步true；未同步：false
};
//本应该存储Base里面的数据，考虑到模块跳转的问题，存了所有state
const updateBaseStore = function(state){
  let baseStore = {}
  Object.keys(state).forEach(key=>{
    baseStore[key] = state[key]
  })
  $local(baseStoreState,baseStore);
}
const baseStore = {
  state: {
    ...Base,
    ...lastBaseStore,
    metaState: false,
    proid: window.localStorage.getItem('solft_proid'),
  },
  getters:{
    token: (state: BaseState) => state.token,
    info: (state: BaseState) => state.info,
    netState: (state: BaseState) => state.netState,
    updateState: (state: BaseState) => state.updateState,
    metaState: (state: BaseState) => state.metaState,
    meta: (state: BaseState) => state.meta,
    deviceInfo: (state: BaseState) => state.deviceInfo
  },
  mutations: {
    setBaseStoreState: (state: BaseState, params:Record<string,any>|null) => {
      if(params && isObject(params)){
        Object.keys(Base).forEach(key=>{
          if(key in params){
            state[key] = params[key];
          }
        })
      }else{
        Object.keys(state).forEach(key=>{
          if(key in Base){
            state[key] = Base[key];
          }else{
            delete state[key]
          }    
        })
      }
      updateBaseStore(state);
    },
    changeNetState:(state: BaseState)=>{
      state.netState = !state.netState;
      state.updateState = false;//只要状态变更，就重置为未同步
      updateBaseStore(state);
    },
    changeUpdateState:(state: BaseState,bol:boolean)=>{
      state.updateState = bol;
      updateBaseStore(state);
    },
    setNewData(state: BaseState,params:Record<string,any>){
      Object.keys(params).forEach(key=>{
        if(key in Base)return;//设置数据不允许设置base数据（防止误操作）
        state[key] = params[key];
      })
      updateBaseStore(state);
    },
    changeMetaState:(state: BaseState,bol:boolean)=>{
      state.metaState = bol;
      updateBaseStore(state);
    },
    setNewMeta(state: BaseState,params:boolean | Record<string,any>){//更改meta信息
      state.meta = params || {};
      state.metaState = !state.metaState;
      updateBaseStore(state);
    },
  },
  actions: {
    // 登录
    async login ({ commit,getters }:ActionContext<BaseState,any>,params:any) {
      setTimeout(()=>{
        let data = {token:"Demo-token001",user:{name:'张三'}};
        $local(appToken,data.token||'001');
        commit('setBaseStoreState',{
          token: data.token,
          info: data.user
        });
        $pathTo('@'+process.env.VUE_APP_HOME)
      },1000)
      // await request({
      //   url: '/login',
      //   method: 'post',
      //   data:params
      // }).then((res:any)=>{
      //   let data = res.content;
      //   $local(appToken,data.token||'001');
      //   commit('setBaseStoreState',{
      //     token: data.token,
      //     info: data.user
      //   });
      //   $pathTo('@'+process.env.VUE_APP_HOME)
      // });
    },
    // 登出
    async logout ({ commit }:ActionContext<BaseState,any>) {
      window.sessionStorage.clear();
      $local(appToken,null);
      commit('setBaseStoreState',null);
      setTimeout(()=>{
        $pathTo('@'+process.env.VUE_APP_LOGIN)
      },10)
      // return await request({
      //   url: '/logout',
      //   method: 'post',
      //   data:{}
      // }).then((res)=>{
      //   window.sessionStorage.clear();
      //   $local(appToken,null);
      //   commit('setBaseStoreState',null);
      //   setTimeout(()=>{
      //     $pathTo('@'+process.env.VUE_APP_LOGIN)
      //   },10)
      // })
    }
  }
};
$local(baseStoreState,baseStore.state)
export interface BaseState {
  token: string;
  info: any;
  netState?: boolean;
  [propName: string]: any;
};
export default function(store:any){
  store.state = {...baseStore.state,...store.state};
  store.getters = {...baseStore.getters,...store.getters};
  store.mutations = {...baseStore.mutations,...store.mutations};
  store.actions = {...baseStore.actions,...store.actions};
  return store;
}